package com.yjc.blog.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yjc.blog.domain.bo.CateSave;
import com.yjc.blog.domain.bo.ECategoryDao;
import com.yjc.blog.domain.po.Category;
import com.yjc.blog.domain.vo.CategoryVO;
import com.yjc.blog.domain.vo.PageVO;
import com.yjc.blog.mapper.CategoryMapper;
import com.yjc.blog.service.ICategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjc.blog.utils.CopyUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 分类 服务实现类
 * </p>
 *
 * @author yjc
 * @since 2024-10-30
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {

    @Override
    public PageVO<CategoryVO> CateList(ECategoryDao dao) {
        Long cateId = dao.getId();
        String cateName = dao.getName();
        if (ObjectUtil.isNull(cateId) && ObjectUtil.isEmpty(cateName)){
            //查询所有
            PageHelper.startPage(dao.getPage(),dao.getSize());
            List<Category> list = this.list();

            if (list == null){
                return new PageVO<>();
            }
            List<CategoryVO> copyList = CopyUtil.copyList(list, CategoryVO.class);
            PageInfo<CategoryVO> info = new PageInfo<>(copyList);

            PageVO<CategoryVO> vo = new PageVO<>();
            vo.setList(copyList);
            vo.setTotal(info.getTotal());
            return vo;
        }
        //条件查询
        else {
            PageHelper.startPage(dao.getPage(),dao.getSize());
            List<Category> list = this.lambdaQuery()
                    .eq(cateId != null, Category::getId, cateId)
                    .or()
                    .like(cateName != null, Category::getName, cateName)
                    .list();
            if (list == null){
                return new PageVO<>();
            }
            List<CategoryVO> copyList = CopyUtil.copyList(list, CategoryVO.class);
            PageInfo<CategoryVO> info = new PageInfo<>();
            PageVO<CategoryVO> vo = new PageVO<>();
            vo.setTotal(info.getTotal());
            vo.setList(copyList);

            return vo;
        }
    }


    @Override
    public void CateSave(CateSave save) {
        Long id = save.getId();
        Category copy = CopyUtil.copy(save, Category.class);
        //更新操作
        if (id != null){
            this.lambdaUpdate()
                    .update(copy);
        }
        else {
            this.save(copy);
        }
    }

    @Override
    public void cateDelete(Long id) {
        this.removeById(id);
    }

    public List<CategoryVO> all(){
        List<Category> list = this.lambdaQuery()
                .orderByAsc(Category::getSort)
                .list();
        List<CategoryVO> vos = CopyUtil.copyList(list, CategoryVO.class);
        return vos;
    }
}
